package com.example.fairplay.newfpregistration.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fairplay.newfpregistration.R;
import com.example.fairplay.newfpregistration.util.StatusBarCompat;
import com.example.fairplay.newfpregistration.view.DialogTools;
import com.example.mylibrary.config.Config;
import com.example.mylibrary.data.ByteImg;
import com.example.mylibrary.data.DBManager;
import com.example.mylibrary.data.StudentInfo;
import com.example.mylibrary.util.PreferencesUtils;
import com.example.mylibrary.util.ToastUtils;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.aratek.idcard.IDCard;
import cn.com.aratek.idcard.IDCardReader;
import cn.com.aratek.util.Result;

/**
 * Created by fairplay on 2018/6/11.
 */

public class ProjectPickActivity extends BaseActivity {

	@Bind(R.id.imageView)
	ImageView imageView;
	@Bind(R.id.ed_transition)
	EditText edTransition;
	@Bind(R.id.btn_query)
	Button btnQuery;
	@Bind(R.id.btn_scanner)
	Button btnScanner;

	@Bind(R.id.text_title)
	TextView tvTitle;
	@Bind(R.id.button_backward)
	Button btnBack;
	private ProjectPickActivity mActivity;
	private final static int MSG_CARD_INFO = 1;
	private final static int MSG_SHOW_DIALOG = 2;
	private final static int MSG_DISMISS_DIALOG = 3;

	private IDCardReader mReader;
	private IDCard idCard;

	private boolean isReading = true;
	private String stuCode;//身份证号
	private byte[] snapshotFeature;//图像数组
	private byte[] fpbytes;//指纹数组
	private Bitmap cardBitmap;//身份证照片
	private StudentInfo studentInfo;
	private List<ByteImg> byteImgs = new ArrayList<>();
	private ReadThread readThread;
	private ArrayList<ByteImg> bytes;
	private ByteImg byteImg;
	private List<ByteImg> imgList;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_CARD_INFO:
					DialogTools.dismssDialog();
//					idCard = (IDCard) msg.obj;
					Intent intent;
					if (card_finger) {
						intent = new Intent(mActivity, DistinguishFingerActivity.class);
					} else {
						intent = new Intent(mActivity, DistinguishFaceActivity.class);
					}

					Bundle bundle = new Bundle();
					bundle.putString("idCard", idCard.getNumber());
					byte[] fpbytes = idCard.getFingerprint();
					if (fpbytes != null) {
//						bundle.putSerializable("fpinfo", fpbytes);
						intent.putExtra("fpinfo", fpbytes);
					}
					cardBitmap = idCard.getPhoto();
					if (cardBitmap != null) {
						bundle.putParcelable("bitmap", cardBitmap);
					}

					intent.putExtras(bundle);

					startActivity(intent);
					break;
				case MSG_SHOW_DIALOG:
					String info = (String) msg.obj;
					DialogTools.showDialog(mActivity, info);
					break;
				case MSG_DISMISS_DIALOG:
					DialogTools.dismssDialog();
					break;
			}
		}
	};
	private boolean card_finger;


	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_project_pick);
		StatusBarCompat.compat(this, Color.rgb(7, 136, 242));
		mActivity = this;
		ButterKnife.bind(this);
		initObject();
		initView();
		initData();
		setListener();

	}


	@Override
	protected void onResume() {
		super.onResume();
		readCard();

	}

	@Override
	protected void initData() {
		openDevice();
	}

	@Override
	protected void initView() {
		tvTitle.setText("人证验证");
		if (card_finger) {
			edTransition.setEnabled(false);
		}
	}

	@Override
	protected void initObject() {
		card_finger = PreferencesUtils.getBoolean(Config.SETTING_CARD_FINGER, false);
		mReader = IDCardReader.getInstance(mActivity);
	}

	@Override
	protected void setListener() {

		//条码枪 扫描自动跳转
		edTransition.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					// do something
				}
//				manualQuery();
				return true;
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
		if (intentResult != null) {
			if (intentResult.getContents() == null) {
				ToastUtils.Toast(mActivity, "扫描内容为空");
			} else {
				ToastUtils.Toast(mActivity, "扫描成功");
				String scanResult = intentResult.getContents();

				manualQuery(scanResult);

//				studentInfo = DBManager.getInstance(this).queryIdInfo(scanResult);
//				if (studentInfo == null) {
//					ToastUtils.Toast(this, "查无此人");
//					return;
//				}
//				Intent intent = new Intent(mActivity, DistinguishFaceActivity.class);
//				Bundle bundle = new Bundle();
//				bundle.putSerializable("idCard", scanResult);
//				intent.putExtras(bundle);
//				startActivity(intent);
//
//				Log.e("Scanner:", scanResult);
			}
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	@OnClick({R.id.btn_query, R.id.btn_scanner, R.id.button_backward})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.button_backward:
				finish();
				break;
			case R.id.btn_query:
				if (card_finger) {
					ToastUtils.Toast(this, "此模式只支持身份证");
					break;
				}
				String etInfo = edTransition.getText().toString().trim();
				manualQuery(etInfo);
				break;
			case R.id.btn_scanner:
				if (card_finger) {
					ToastUtils.Toast(this, "此模式只支持身份证");
					break;
				}
				new IntentIntegrator(this)
						.setOrientationLocked(false)
						.setCaptureActivity(ScannerActivity.class) // 设置自定义的activity是ScanActivity
						.initiateScan(); // 初始化扫描
				break;
		}
	}

	/**
	 * 根据学号或身份证号查询之后跳转人脸信息页面
	 */
	private void manualQuery(String info) {
		studentInfo = DBManager.getInstance(mActivity).queryStuInfo(info);
		if (TextUtils.isEmpty(info)) {
			Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
		} else if (studentInfo == null) {
			studentInfo = DBManager.getInstance(mActivity).queryIdInfo(info);
			if (studentInfo == null)
				Toast.makeText(this, "查无此人", Toast.LENGTH_SHORT).show();
		} else {
			Intent intent = null;
			if (card_finger) {
//				intent = new Intent(this, DistinguishFingerActivity.class);
//				intent.putExtra("idCard", studentInfo.getIdCard());
			} else {
				intent = new Intent(this, DistinguishFaceActivity.class);
				intent.putExtra("idCard", studentInfo.getIdCard());
			}
			startActivity(intent);
		}
	}

	/**
	 * 打开身份证设备
	 */
	private void openDevice() {
		new Thread() {
			@Override
			public void run() {
				int error;
				showProgressDialog(getString(R.string.preparing_device));
				if ((error = mReader.powerOn()) != IDCardReader.RESULT_OK) {
					dismissProgressDialog();
					return;
				}
				if ((error = mReader.open()) != IDCardReader.RESULT_OK) {
					dismissProgressDialog();
					return;
				}
				dismissProgressDialog();
				readCard();
			}
		}.start();
	}

	private void readCard() {
		isReading = true;
		if (readThread == null) {
			readThread = new ReadThread();
			readThread.start();
		}
	}

	/**
	 * 识别身份证线程
	 */
	private class ReadThread extends Thread {
		public void run() {
			Result res;
			do {
				res = mReader.read();
			} while (res.error != IDCardReader.RESULT_OK && isReading == true);
			if (res.error == IDCardReader.RESULT_OK) {
				showProgressDialog(getString(R.string.id_card_read_success));
				mHandler.sendMessage(mHandler.obtainMessage(MSG_CARD_INFO, (IDCard) res.data));
				idCard = (IDCard) res.data;
				final Result temp = res;
				idCard.getFingerprint();
				//clearFeature();
				stuCode = idCard.getNumber();
				//将查询到的数据给数组
				stopReading();

			} else {

			}
		}

	}

	/**
	 * 关闭device
	 */
	private void closeDevice() {
		new Thread() {
			@Override
			public void run() {
				int error;
				isReading = false;
				readThread = null;
				if ((error = mReader.close()) != IDCardReader.RESULT_OK) {

					return;
				}
				if ((error = mReader.powerOff()) != IDCardReader.RESULT_OK) {

					return;
				}

			}
		}.start();
	}

	private void stopReading() {
		isReading = false;
		readThread = null;

	}

	/**
	 * 显示对话框
	 *
	 * @param message
	 */
	private void showProgressDialog(String message) {
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_DIALOG,
				message));
	}

	private void dismissProgressDialog() {
		mHandler.sendMessage(mHandler
				.obtainMessage(MSG_DISMISS_DIALOG));
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		closeDevice();
	}
}
